package com.yym.selevlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;

@WebServlet(value = "/file", name = "FileServlet", loadOnStartup = 1)
@MultipartConfig  /** 告诉该Servlet，你要处理的是一个 “多媒体的表单数据”  */
public class FileServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        System.out.println("FileServlet method invoked .....");
    }

    private String fileLocation = "D:/nginx-server/nginx-1.17.2/images/";
//D:\wp\Servlet\LoginServlet\web\images\753f1694-e7c4-4476-a941-ebe72fbba881.jpg
//    web\images\753f1694-e7c4-4476-a941-ebe72fbba881.jpg
    //jetbrains://idea/navigate/reference?project=LoginServlet&path=images/753f1694-e7c4-4476-a941-ebe72fbba881.jpg
    private String fileServer = "http://localhost/";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取上传的文件的所有的信息，part中封装要上传的文件的所有信息
        // <input type="file" name="avatar"><br>
        Part part = req.getPart("fileupload");

        // part.getName(); //通过part.getName() 得到不是文件名
        //获取文件的名字, 文件名是在Part的头部, "content-disposition"中存储有文件名
        // contentDisposition的数据内容是： form-data; name="avatar"; filename="4月8日复习.txt"
        String contentDisposition = part.getHeader("content-disposition");

        String filePrefix = "filename=\"";  // \n \t \"

        //获取文件名开始位置所在的索引
        int index = contentDisposition.indexOf(filePrefix) + filePrefix.length();

        //获取文件名， contentDisposition.length() - 1 原因是因为最后有个 "
        String fileName = contentDisposition.substring(index, contentDisposition.length() - 1);

        // 获取文件的后缀名: .png  .txt  .jpg
        String fileSuffix = fileName.substring(fileName.indexOf("."));

        //  UUID.randomUUID().toString() 随机生成一个字符串
        String newFileName = UUID.randomUUID().toString() + fileSuffix;

        InputStream is = part.getInputStream();   //获取文件的输入流

        //文件输出流
        OutputStream os = new FileOutputStream(fileLocation + newFileName);

        // 存储IO流每次读取的数据
        byte[] bs = new byte[1024];
        int length = 0; //每次读取的长度

        while(-1 != (length = is.read(bs))) {
            os.write(bs, 0, length);
        }
        os.flush();
        os.close();
        is.close();

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        StringBuffer html = new StringBuffer();
        html.append("<html>")
                .append("<head></head>")
                .append("<body><h1>上</h1>")
                // fileServer + newFileName = http://localhost/0dc725b1-5b12-4865-bbd0-2fbed66b9e7e.png
                .append("<img src=\"" + fileServer + newFileName + "\">")
                .append("<video src=\"" + fileServer + newFileName + "\" width=\"600\" height=\"400\" autoplay>")
                .append("</body></html>");

//        String html = "<html><head></head><body><h1>注册成功</h1><p>" + user.getInterests() + "</p></body></html>";

        writer.write(html.toString());
        writer.flush();
        writer.close();
    }
}
